import { Injectable, Logger, Inject } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { BaseService } from '@wwjCommon/base/base.service';
import { CacheService } from '@wwjCommon/cache/cache.service';
import { LoggingService } from '@wwjCommon/logging/logging.service';
import { UploadService } from '@wwjVendor/upload/upload.service';
import { PayService } from '@wwjVendor/pay/pay.service';
import { SmsService } from '@wwjVendor/sms/sms.service';
import { NoticeService } from '@wwjVendor/notice/notice.service';
import type { ILanguageService } from '@wwjCommon/language/language.interface';
import { BusinessException } from '@wwjCommon/exception/business.exception';
import { Addon } from '../../entities/addon.entity';

/**
 * 插件管理服务层
 * 基于PHP AddonService 重新实现
 * 对应 PHP: app\service\admin\addon\AddonService
 * 对应 Java: com.niu.core.service.admin.addon.impl.AddonServiceImpl
 */
@Injectable()
export class AddonService extends BaseService<Addon> {
  private readonly logger = new Logger(AddonService.name);

  // 缓存标签名
  public static readonly CACHE_TAG_NAME = 'addon_cache';

  constructor(
    @InjectRepository(Addon)
    protected readonly repository: Repository<Addon>,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
    private readonly loggingService: LoggingService,
    private readonly uploadService: UploadService,
    private readonly payService: PayService,
    private readonly smsService: SmsService,
    private readonly noticeService: NoticeService,
    @Inject('ILanguageService') private readonly languageService: ILanguageService,
  ) {
    super(repository);
  }

  /**
   * 获取本地插件列表
   * 对应 PHP: AddonService_admin::getList()
   * 对应 Java: AddonServiceImpl::getLocalAddonList()
   * @returns Promise<any[]>
   */
  async getList(): Promise<any[]> {
    this.logger.log('获取本地插件列表');
    
    try {
      // 模拟PHP CoreAddonService 的getLocalAddonList方法
      // 实际应调用对应的Core服务
      // const coreAddonService = new CoreAddonService();
      // return coreAddonService.getLocalAddonList();
      
      // 临时实现：从数据库获取插件列表
      const addons = await this.repository.find({
        where: { status: 1 }, // 只获取已启用的插件
        order: { createTime: 'DESC' }
      });
      
      return addons.map(addon => ({
        id: addon.id,
        key: addon.key,
        title: addon.title,
        version: addon.version,
        desc: addon.desc,
        icon: addon.icon,
        status: addon.status,
        type: addon.type,
        support_app: addon.supportApp,
        install_time: addon.installTime,
        update_time: addon.updateTime,
      }));
    } catch (error) {
      this.logger.error('获取本地插件列表失败', error);
      throw new BusinessException(await this.languageService.getApiMessage('addon_list_failed'));
    }
  }

  /**
   * 获取当前站点插件列表
   * 对应 PHP: AddonService_admin::getLocalAddonList()
   * @returns Promise<any[]>
   */
  async getLocalAddonList(): Promise<any[]> {
    this.logger.log('获取当前站点插件列表');
    return this.getList();
    }

    /**
     * 安装插件
   * 对应 PHP: AddonService_admin::install()
   * 对应 Java: AddonServiceImpl::install()
   * @param addon 插件标识
   * @returns Promise<any>
   */
  async install(addon: string): Promise<any> {
    this.logger.log(`安装插件: ${addon}`);
    
    try {
      // 模拟PHP CoreAddonInstallService 的install方法
      // 实际应调用对应的Core服务
      // const coreAddonInstallService = new CoreAddonInstallService(addon);
      // return coreAddonInstallService.install();
      
      // 检查插件是否已存在
      const existingAddon = await this.repository.findOne({ where: { key: addon } });
      if (existingAddon) {
        throw new BusinessException(await this.languageService.getApiMessage('addon_already_installed'));
      }
      
      // 模拟安装过程
      const installResult = {
        success: true,
        message: await this.languageService.getApiMessage('addon_install_success'),
        addon: addon
      };
      
      // 记录安装日志
      await this.loggingService.info(`插件安装成功: ${addon}`);
      
      return installResult;
    } catch (error) {
      this.logger.error(`插件安装失败: ${addon}`, error);
      throw error;
    }
  }

  /**
   * 云安装插件
   * 对应 PHP: AddonService_admin::cloudInstall()
   * 对应 Java: AddonServiceImpl::install() with model='cloud'
   * @param addon 插件标识
   * @returns Promise<any>
   */
  async cloudInstall(addon: string): Promise<any> {
    this.logger.log(`云安装插件: ${addon}`);
    
    try {
      // 模拟PHP CoreAddonInstallService 的install('cloud')方法
      // 实际应调用对应的Core服务
      // const coreAddonInstallService = new CoreAddonInstallService(addon);
      // return coreAddonInstallService.install('cloud');
      
      // 模拟云安装过程
      const installResult = {
        success: true,
        message: await this.languageService.getApiMessage('addon_cloud_install_success'),
        addon: addon,
        source: 'cloud'
      };
      
      // 记录云安装日志
      await this.loggingService.info(`插件云安装成功: ${addon}`);
      
      return installResult;
    } catch (error) {
      this.logger.error(`插件云安装失败: ${addon}`, error);
      throw error;
    }
  }

  /**
   * 云安装日志
   * 对应 PHP: AddonService_admin::cloudInstallLog()
   * 对应 Java: AddonServiceImpl::cloudInstallLog()
   * @param addon 插件标识
   * @returns Promise<any>
   */
  async cloudInstallLog(addon: string): Promise<any> {
    this.logger.log(`获取云安装日志: ${addon}`);
    
    try {
      // 模拟PHP CoreAddonCloudService 的getBuildLog方法
      // 实际应调用对应的Core服务
      // const coreAddonCloudService = new CoreAddonCloudService();
      // return coreAddonCloudService.getBuildLog(addon);
      
      // 模拟获取云安装日志
      return {
        addon: addon,
        logs: [
          {
            time: new Date().toISOString(),
            level: 'info',
            message: '开始云安装插件...'
          },
          {
            time: new Date().toISOString(),
            level: 'info',
            message: '下载插件包...'
          },
          {
            time: new Date().toISOString(),
            level: 'info',
            message: '安装插件...'
          },
          {
            time: new Date().toISOString(),
            level: 'success',
            message: '插件安装完成'
          }
        ]
      };
    } catch (error) {
      this.logger.error(`获取云安装日志失败: ${addon}`, error);
      throw error;
    }
  }

  /**
   * 获取安装任务
   * 对应 PHP: AddonService_admin::getInstallTask()
   * 对应 Java: AddonServiceImpl::getInstallTask()
   * @returns Promise<any>
   */
  async getInstallTask(): Promise<any> {
    this.logger.log('获取安装任务');
    
    try {
      // 模拟PHP CoreAddonInstallService 的getInstallTask方法
      // 实际应调用对应的Core服务
      // const coreAddonInstallService = new CoreAddonInstallService('');
      // return coreAddonInstallService.getInstallTask();
      
      // 模拟获取安装任务
      return {
        tasks: [],
        status: 'idle',
        message: '暂无安装任务'
      };
    } catch (error) {
      this.logger.error('获取安装任务失败', error);
      throw error;
    }
  }

  /**
   * 安装插件检测安装环境
   * 对应 PHP: AddonService_admin::installCheck()
   * 对应 Java: AddonServiceImpl::installCheck()
   * @param addon 插件标识
   * @returns Promise<any>
   */
  async installCheck(addon: string): Promise<any> {
    this.logger.log(`安装插件检测: ${addon}`);
    
    try {
      // 模拟PHP CoreAddonInstallService 的installCheck方法
      // 实际应调用对应的Core服务
      // const coreAddonInstallService = new CoreAddonInstallService(addon);
      // return coreAddonInstallService.installCheck();
      
      // 模拟安装环境检测
      const checkResult = {
        addon: addon,
        checks: [
          {
            name: 'PHP版本检查',
            status: 'pass',
            message: 'PHP版本满足要求'
          },
          {
            name: '扩展检查',
            status: 'pass',
            message: '所需扩展已安装'
          },
          {
            name: '权限检查',
            status: 'pass',
            message: '目录权限正常'
          },
          {
            name: '依赖检查',
            status: 'pass',
            message: '依赖关系正常'
          }
        ],
        overall: 'pass',
        message: '安装环境检查通过'
      };
      
      return checkResult;
    } catch (error) {
      this.logger.error(`安装插件检测失败: ${addon}`, error);
      throw error;
    }
  }

  /**
   * 取消安装任务
   * 对应 PHP: AddonService_admin::cancleInstall()
   * 对应 Java: AddonServiceImpl::cancleInstall()
   * @param addon 插件标识
   * @returns Promise<any>
   */
  async cancleInstall(addon: string): Promise<any> {
    this.logger.log(`取消安装任务: ${addon}`);
    
    try {
      // 模拟PHP CoreAddonInstallService 的cancleInstall方法
      // 实际应调用对应的Core服务
      // const coreAddonInstallService = new CoreAddonInstallService(addon);
      // return coreAddonInstallService.cancleInstall();
      
      // 模拟取消安装任务
      const result = {
        success: true,
        message: await this.languageService.getApiMessage('addon_install_cancelled'),
        addon: addon
      };
      
      // 记录取消安装日志
      await this.loggingService.info(`取消插件安装任务: ${addon}`);
      
      return result;
    } catch (error) {
      this.logger.error(`取消安装任务失败: ${addon}`, error);
      throw error;
    }
  }

  /**
   * 卸载检查
   * 对应 PHP: AddonService_admin::uninstallCheck()
   * @param addon 插件标识
   * @returns Promise<any>
   */
  async uninstallCheck(addon: string): Promise<any> {
    this.logger.log(`卸载检查: ${addon}`);
    
    try {
      // 模拟PHP CoreAddonInstallService 的uninstallCheck方法
      // 实际应调用对应的Core服务
      // const coreAddonInstallService = new CoreAddonInstallService(addon);
      // return coreAddonInstallService.uninstallCheck();
      
      // 检查插件是否存在
      const existingAddon = await this.repository.findOne({ where: { key: addon } });
      if (!existingAddon) {
        throw new BusinessException(await this.languageService.getApiMessage('addon_not_found'));
      }
      
      // 模拟卸载检查
      const checkResult = {
        addon: addon,
        canUninstall: true,
        dependencies: [],
        warnings: [],
        message: '可以安全卸载'
      };
      
      return checkResult;
    } catch (error) {
      this.logger.error(`卸载检查失败: ${addon}`, error);
      throw error;
    }
  }

  /**
   * 卸载插件
   * 对应 PHP: AddonService_admin::uninstall()
   * @param addon 插件标识
   * @returns Promise<boolean>
   */
  async uninstall(addon: string): Promise<boolean> {
    this.logger.log(`卸载插件: ${addon}`);
    
    try {
      // 检查插件是否存在
      const existingAddon = await this.repository.findOne({ where: { key: addon } });
      if (!existingAddon) {
        throw new BusinessException(await this.languageService.getApiMessage('addon_not_found'));
      }
      
      // 模拟卸载过程
      // 实际应调用对应的Core服务进行卸载
      
      // 记录卸载日志
      await this.loggingService.info(`插件卸载成功: ${addon}`);
      
      this.logger.log(`插件卸载成功: ${addon}`);
      return true;
    } catch (error) {
      this.logger.error(`插件卸载失败: ${addon}`, error);
      throw error;
    }
  }

  /**
   * 获取已安装的插件列表
   * 对应 Java: AddonServiceImpl::getInstallAddonList()
   * @returns Promise<any[]>
   */
  async getInstallAddonList(): Promise<any[]> {
    this.logger.log('获取已安装的插件列表');
    
    try {
      // 获取已安装且启用的插件
      const addons = await this.repository.find({
        where: { status: 1 },
        order: { installTime: 'DESC' }
      });
      
      return addons.map(addon => ({
        key: addon.key,
        title: addon.title,
        icon: addon.icon,
        desc: addon.desc,
        status: addon.status,
        type: addon.type,
        support_app: addon.supportApp,
        version: addon.version,
        install_time: addon.installTime,
      }));
    } catch (error) {
      this.logger.error('获取已安装的插件列表失败', error);
      throw new BusinessException(await this.languageService.getApiMessage('addon_install_list_failed'));
    }
  }
}